/*
 * @ProjectName: flutter_common
 * @Package: 
 * @ClassName: forget_password.dart
 * @Description: 忘记密码页面
 * @User: Page.Su
 * @Date: 2020/8/25
 * @Time: 16:06
 * @UpdateDate: 2020/8/25 16:06
 */

import 'dart:async';

import 'package:fdottedline/fdottedline.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_su/common/app_color.dart';
import 'package:flutter_su/common/fun.dart';
import 'package:flutter_su/common/input_check.dart';
import 'package:flutter_su/common/language_text.dart';
import 'package:flutter_su/enum/language_type.dart';

class ForgetPassword extends StatefulWidget {
  @override
  _ForgetPasswordState createState() => _ForgetPasswordState();
}

class _ForgetPasswordState extends State<ForgetPassword> {
  // 控制注册按钮刷新
  StreamController<String> _disableShowController =
      StreamController.broadcast();

  // 显示输入框底部虚线
  StreamController<bool> _hiddenTextFileLineByEmail = StreamController();
  StreamController<bool> _hiddenTextFileLineByEmailCode = StreamController();
  StreamController<bool> _hiddenTextFileLineByPassword = StreamController();
  StreamController<bool> _hiddenTextFileLineBySecondPassword =
      StreamController();
  StreamController<int> _emailButtonTimeOut = StreamController.broadcast();

  // 输入框
  TextEditingController _emailInputController = TextEditingController();
  TextEditingController _emailInputCodeController = TextEditingController();
  TextEditingController _passwordInputController = TextEditingController();
  TextEditingController _secondPasswordInputController =
      TextEditingController();

  // 控制错误显示
  StreamController<String> _showErrorMessageController = StreamController();

  int _timeOut = 5; // 倒计时秒数
  bool _isTimeOutIng = false;

  final int emailNoCheck = -1;
  final int emailHasCheck = -2;

  @override
  void dispose() {
    _disableShowController.close();

    _hiddenTextFileLineByEmail.close();
    _emailInputController.dispose();

    _passwordInputController.dispose();
    _emailInputCodeController.dispose();
    _secondPasswordInputController.dispose();

    _hiddenTextFileLineByPassword.close();
    _hiddenTextFileLineBySecondPassword.close();
    _hiddenTextFileLineByEmailCode.close();

    _showErrorMessageController.close();

    _emailButtonTimeOut.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: LanguageText.forgetPasswordByAppBar,
        centerTitle: true,
        elevation: 0,
        backgroundColor: AppColor.MAIN_COLOR_BLUE,
      ),
      backgroundColor: AppColor.MAIN_COLOR_BLUE,
      body: _body(),
    );
  }

  Widget _body() {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: SingleChildScrollView(
        child: Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              _input(),
              _registerButton(),
            ],
          ),
        ),
      ),
    );
  }

  // 所有输入输入框
  Widget _input() {
    return Container(
      margin: EdgeInsets.only(
        left: SFunCommon.width(36),
        right: SFunCommon.width(36),
      ),
      padding: EdgeInsets.only(
        top: SFunCommon.height(250),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          _inputEmail(),
          _inputEmailCodeBox(),
          _inputPassword(),
          _inputSecondPassword(),
          _registerTipText(),
        ],
      ),
    );
  }

  Widget _registerTipText() {
    return StreamBuilder(
      initialData: '',
      stream: _showErrorMessageController.stream,
      builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
        return Offstage(
          offstage: snapshot.data.isEmpty,
          child: SFunCommon.text(
            SFunCommon.fontStyle(
              AppColor.MAIN_COLOR_CYAN,
              fontSize: 30,
            ),
            contentType: ContentType.loginRegister,
            key: snapshot.data.isEmpty ? "null" : snapshot.data,
          ),
        );
      },
    );
  }

  Widget _inputEmail() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        LanguageText.inputEmailToSendCode,
        _emailTextField(),
        _lineByEmail(),
      ],
    );
  }

  Widget _emailTextField() {
    return Container(
      width: SFunCommon.width(500),
      height: SFunCommon.height(52),
      child: TextField(
        keyboardType: TextInputType.emailAddress,
        controller: _emailInputController,
        style: SFunCommon.fontStyle(
          AppColor.MAIN_INPUT_COLOR,
          fontSize: 31,
        ),
        cursorColor: AppColor.MAIN_INPUT_COLOR,
        decoration: _inputDecoration(),
        onChanged: (String value) {
          if (value.length > 0) {
            _hiddenTextFileLineByEmail.sink.add(true);
            _disableShowController.sink.add(value);

            // 正则判断邮箱
            String message = FunCommon().checkEmail(_emailInputController.text,
                message: "emailFormatError");
            _showErrorMessageController.sink.add(message);

            // 控制获取验证码按钮
            if (message.isNotEmpty) {
              _emailButtonTimeOut.sink.add(emailNoCheck);
            } else {
              _emailButtonTimeOut.sink.add(emailHasCheck);
            }
          } else {
            _hiddenTextFileLineByEmail.sink.add(false);
          }
        },
      ),
    );
  }

  // 校验邮箱是否正确
  String _checkPasswordSame() {
    Map<String, List<Map<String, dynamic>>> rules = {
      "secondPassword": [
        {
          ValidateInput.EQUAL: _passwordInputController.text,
          ValidateInput.MESSAGE: "inputRegisterPasswordError",
        },
      ],
    };
    Map<String, dynamic> params = {
      "secondPassword": _secondPasswordInputController.text,
    };
    var validate = ValidateInput(
      rules: rules,
      params: params,
    );
    return validate.message;
  }

  // 输入验证码
  Widget _inputEmailCodeBox() {
    return Row(
      children: <Widget>[
        Expanded(
          flex: 3,
          child: _inputPEmailCode(),
        ),
        Expanded(
          flex: 2,
          child: _emailButton(),
        ),
      ],
    );
  }

  // 获取验证码按钮
  Widget _emailButton() {
    Widget _emailButtonStream = StreamBuilder(
      initialData: 0,
      stream: _emailButtonTimeOut.stream,
      builder: (_, AsyncSnapshot<int> snapshot) {
        Widget text = LanguageText.getEmailCode;
        if (_isTimeOutIng) {
          text = Text("${snapshot.data}S");
        }
        return Container(
          width: SFunCommon.width(200),
          height: SFunCommon.height(78),
          child: RaisedButton(
            textColor: AppColor.MAIN_COLOR_BLUE,
            color: AppColor.MAIN_COLOR_CYAN,
            disabledColor: AppColor.MAIN_COLOR_CYAN_DISABLE,
            // 等于-1的时候，代表邮箱格式不对
            onPressed: (!_isTimeOutIng && snapshot.data == emailHasCheck)
                ? _getEmailCodeTimeOut
                : null,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(SFunCommon.width(20))),
            child: text,
          ),
        );
      },
    );

    return _emailButtonStream;
  }

  // 开始倒计时
  void _getEmailCodeTimeOut() async {
    _isTimeOutIng = true;
    Duration interval = Duration(seconds: 1);
    Stream<int> stream = Stream.periodic(interval, (data) => data);
    stream = stream.take(_timeOut);
    await for (int i in stream) {
      if (i == (_timeOut - 1)) {
        _isTimeOutIng = false;
        _emailButtonTimeOut.sink.add(emailHasCheck);
      } else {
        _emailButtonTimeOut.sink.add(_timeOut - i - 1);
      }
    }
  }

  Widget _inputPEmailCode() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        LanguageText.inputEmailCode,
        _inputEmailCodeField(),
        _lineByEmailCode(),
      ],
    );
  }

  Widget _inputEmailCodeField() {
    return Container(
//      width: SFunCommon.width(500),
      height: SFunCommon.height(52),
      child: TextField(
        controller: _emailInputCodeController,
        keyboardType: TextInputType.number,
        style: SFunCommon.fontStyle(
          AppColor.MAIN_INPUT_COLOR,
          fontSize: 30,
        ),
        inputFormatters: <TextInputFormatter>[
          LengthLimitingTextInputFormatter(6) //限制长度
        ],
        cursorColor: AppColor.MAIN_INPUT_COLOR,
        decoration: _inputDecoration(),
        onChanged: (String value) {
          if (value.length > 0) {
            _hiddenTextFileLineByEmailCode.sink.add(true);
            _disableShowController.sink.add(value);
          } else {
            _hiddenTextFileLineByEmailCode.sink.add(false);
          }
        },
      ),
    );
  }

  Widget _inputPassword() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        LanguageText.inputNewPassword,
        _passwordField(),
        _lineByPassword(),
      ],
    );
  }

  Widget _passwordField() {
    return Container(
      width: SFunCommon.width(500),
      height: SFunCommon.height(52),
      child: TextField(
        controller: _passwordInputController,
        style: SFunCommon.fontStyle(
          AppColor.MAIN_INPUT_COLOR,
          fontSize: 30,
        ),
        obscureText: true,
        cursorColor: AppColor.MAIN_INPUT_COLOR,
        decoration: _inputDecoration(),
        onChanged: (String value) {
          if (value.length > 0) {
            _hiddenTextFileLineByPassword.sink.add(true);
            _disableShowController.sink.add(value);
//
            var message = _checkPasswordSame();
            _showErrorMessageController.sink.add(message);
          } else {
            _hiddenTextFileLineByPassword.sink.add(false);
          }
        },
      ),
    );
  }

  Widget _inputSecondPassword() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        LanguageText.inputSecondNewPassword,
        _secondPasswordField(),
        _lineBySecondPassword(),
      ],
    );
  }

  Widget _secondPasswordField() {
    return Container(
      width: SFunCommon.width(500),
      height: SFunCommon.height(52),
      child: TextField(
        controller: _secondPasswordInputController,
        style: SFunCommon.fontStyle(
          AppColor.MAIN_INPUT_COLOR,
          fontSize: 30,
        ),
        obscureText: true,
        cursorColor: AppColor.MAIN_INPUT_COLOR,
        decoration: _inputDecoration(),
        onChanged: (String value) {
          if (value.length > 0) {
            _hiddenTextFileLineBySecondPassword.sink.add(true);
            _disableShowController.sink.add(value);

            var message = _checkPasswordSame();
            _showErrorMessageController.sink.add(message);

          } else {
            _hiddenTextFileLineBySecondPassword.sink.add(false);
          }
        },
      ),
    );
  }

  // 输入框装饰器
  InputDecoration _inputDecoration() {
    return InputDecoration(
      // 未获得焦点下划线设为灰色
      enabledBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: AppColor.MAIN_COLOR_BLUE),
      ),
      //获得焦点下划线设为蓝色
      focusedBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: AppColor.MAIN_COLOR_BLUE),
      ),
    );
  }

  // 邮箱下划线
  Widget _lineByEmail() {
    return StreamBuilder(
      initialData: false,
      stream: _hiddenTextFileLineByEmail.stream,
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        return _line(snapshot.data);
      },
    );
  }

  // 密码下划线
  Widget _lineByEmailCode() {
    return StreamBuilder(
      initialData: false,
      stream: _hiddenTextFileLineByEmailCode.stream,
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        return _line(snapshot.data);
      },
    );
  }

  // 密码下划线
  Widget _lineByPassword() {
    return StreamBuilder(
      initialData: false,
      stream: _hiddenTextFileLineByPassword.stream,
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        return _line(snapshot.data);
      },
    );
  }

  // 再次输入密码下划线
  Widget _lineBySecondPassword() {
    return StreamBuilder(
      initialData: false,
      stream: _hiddenTextFileLineBySecondPassword.stream,
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        return _line(snapshot.data);
      },
    );
  }

  // 一条虚线
  Widget _line(bool data) {
    return Container(
      margin: EdgeInsets.only(
        bottom: SFunCommon.height(40),
      ),
      child: Offstage(
        offstage: data,
        child: FDottedLine(
          color: Colors.white,
          width: SFunCommon.width(336),
          strokeWidth: 2.0,
          dottedLength: 10.0,
          space: 2.0,
        ),
      ),
    );
  }

  // 注册按钮
  Widget _registerButton() {
    Widget _streamRegisterButton = StreamBuilder(
      stream: _disableShowController.stream,
      builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
        bool checkEmail = (FunCommon().checkEmail(_emailInputController.text)).isEmpty ? true : false;
        bool checkEmailCode = _emailInputCodeController.text.length == 6 ? true : false;
        bool password = _checkPasswordSame().isEmpty ? true : false;
        return RaisedButton(
          color: AppColor.MAIN_COLOR_CYAN,
          disabledColor: AppColor.MAIN_COLOR_CYAN_DISABLE,
          onPressed: (checkEmail && checkEmailCode && password) ? (){} : null,
          child: LanguageText.registerText,
          textColor: AppColor.MAIN_COLOR_BLUE,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(SFunCommon.width(20))),
        );
      },
    );

    Widget _button = Container(
      margin: EdgeInsets.only(
        top: SFunCommon.height(250),
        bottom: SFunCommon.height(150),
      ),
      width: SFunCommon.width(569),
      height: SFunCommon.height(75),
      child: _streamRegisterButton,
    );

    return Container(
      alignment: Alignment.center,
      child: _button,
    );
  }
}
